package com.ray.business.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ray.base.check.CustomerCheck;
import com.ray.base.service.BaseCustomerService;
import com.ray.base.service.compose.GoodsService;
import com.ray.base.table.entity.BaseCustomer;
import com.ray.base.table.vo.material.model.MaterialModelVO;
import com.ray.business.builder.SaleBuilder;
import com.ray.business.builder.SaleGoodsBuilder;
import com.ray.business.builder.SaleRecordBuilder;
import com.ray.business.check.SaleCheck;
import com.ray.business.enums.SaleStatusEnum;
import com.ray.business.service.ProdSaleBackService;
import com.ray.business.service.ProdSaleOutService;
import com.ray.business.service.ProdSaleRecordService;
import com.ray.business.service.ProdSaleService;
import com.ray.business.table.dto.SaleQueryDTO;
import com.ray.business.table.entity.ProdSale;
import com.ray.business.table.entity.ProdSaleRecord;
import com.ray.business.table.params.sale.SaleCreateParams;
import com.ray.business.table.params.sale.SaleEditParams;
import com.ray.business.table.params.sale.SaleQueryParams;
import com.ray.business.table.vo.SaleGoodsVO;
import com.ray.business.table.vo.SaleVO;
import com.ray.common.SysMsgCodeConstant;
import com.ray.finance.enums.BillSourceEnum;
import com.ray.finance.table.params.bill.BillCreateParams;
import com.ray.magicBlock.BlockDispatch;
import com.ray.system.builder.CommonPageBuilder;
import com.ray.system.enums.FileTypeEnum;
import com.ray.system.service.SysFileService;
import com.ray.system.table.entity.SysFile;
import com.ray.util.FileRecordUtil;
import com.ray.validate.support.utils.ValidateUtil;
import com.ray.wms.service.WmsWarehouseService;
import com.ray.wms.table.entity.WmsWarehouse;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.config.SysFileConfig;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.page.CommonPage;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.Assert;
import com.ray.woodencreate.util.LogInUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description: 采购相关接口
 * @Class: SaleApi
 * @Package com.ray.business.api
 * @date 2020/6/7 17:52
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Service
@Slf4j
public class SaleApi {

    @Autowired
    private ProdSaleService prodSaleService;
    @Autowired
    private ProdSaleRecordService prodSaleRecordService;
    @Autowired
    private BaseCustomerService baseCustomerService;
    @Autowired
    private WmsWarehouseService wmsWarehouseService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ProdSaleBackService prodSaleBackService;
    @Autowired
    private ProdSaleOutService prodSaleOutService;
    @Autowired
    private BlockDispatch<BillCreateParams, LoginUser, String> createDispatch;
    @Autowired
    private SysFileService sysFileService;
    @Autowired
    private SysFileConfig sysFileConfig;

    /**
     * 查询采购订单列表信息 分页  非删除的
     *
     * @param queryParams
     * @return
     */
    public Result<IPage<SaleVO>> pageSales(CommonPage<SaleQueryParams, Page<SaleVO>> queryParams) {
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        Map<String, WmsWarehouse> wmsWarehouseMap = new HashMap<>();
        Map<String, BaseCustomer> baseCustomerMap = new HashMap<>();
        CommonPageBuilder<SaleQueryDTO, ProdSale> commonPageBuilder = new CommonPageBuilder<>(SaleQueryDTO.class);
        commonPageBuilder.appendEntity(queryParams.getEntity()).appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());
        IPage<ProdSale> page = prodSaleService.page(commonPageBuilder.bulid(), loginUser);
        List<ProdSale> orders = page.getRecords();
        //结果对象
        IPage<SaleVO> pageList = new Page<>();
        pageList.setTotal(page.getTotal());
        pageList.setCurrent(page.getCurrent());
        pageList.setSize(page.getSize());
        //查询到结果 数据转换
        if (ObjectUtil.isNotNull(orders)) {
            pageList.setRecords(orders.stream().map(sysSale -> {
                SaleVO orderVO = new SaleVO();
                BeanUtil.copyProperties(sysSale, orderVO);
                //查询客信息
                BaseCustomer baseCustomer = baseCustomerMap.get(sysSale.getCustomerCode());
                if (ObjectUtil.isEmpty(baseCustomer)) {
                    baseCustomer = baseCustomerService.queryCustomerByCustomerCode(sysSale.getCustomerCode(), loginUser);
                    baseCustomerMap.put(sysSale.getCustomerCode(), baseCustomer);
                }
                orderVO.setCustomerName(baseCustomer.getCustomerName());
                //查询仓库信息
                WmsWarehouse wmsWarehouse = wmsWarehouseMap.get(sysSale.getWarehouseCode());
                if (ObjectUtil.isEmpty(wmsWarehouse)) {
                    wmsWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(sysSale.getWarehouseCode(), loginUser);
                    wmsWarehouseMap.put(wmsWarehouse.getWarehouseCode(), wmsWarehouse);
                }
                orderVO.setWarehouseName(wmsWarehouse.getWarehouseName());
                return orderVO;
            }).collect(Collectors.toList()));
        } else {
            pageList.setRecords(new ArrayList<>());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, pageList);
    }


    /**
     * 创建订单
     *
     * @param createParams 创建对象
     * @return Result
     */
    @Transactional
    public Result<String> createOrder(SaleCreateParams createParams) {
        ValidateUtil.validate(createParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //查询客户数据
        BaseCustomer baseCustomer = baseCustomerService.queryCustomerByCustomerCode(createParams.getCustomerCode(), loginUser);
        new CustomerCheck(baseCustomer).checkNull("客户不存在");
        SaleBuilder orderBuilder = new SaleBuilder();
        orderBuilder.append(createParams).appendStatus(SaleStatusEnum.UN_CHECK.getValue()).appendCreate(loginUser);
        //保存商品信息
        List<String> keys = new ArrayList<>();
        final List<BigDecimal> quantity = new ArrayList<>();
        List<ProdSaleRecord> records = createParams.getGoods().stream().map(saleGoodsParams -> {
            if (keys.contains(saleGoodsParams.getKey())) {
                log.info("存在相同的物料:{}", saleGoodsParams.getKey());
                throw BusinessExceptionFactory.newException("存在相同的物料");
            }
            //销售订单数量
            quantity.add(saleGoodsParams.getQuantity());
            keys.add(saleGoodsParams.getKey());
            return new SaleRecordBuilder().append(saleGoodsParams).appendCode(orderBuilder.getCode()).appendCreate(loginUser).bulid();
        }).collect(Collectors.toList());
        //保存总数
        orderBuilder.append(quantity.stream().reduce(BigDecimal::add).get());
        //保存总价
        orderBuilder.appendTotal(new BigDecimal(0));
        //保存订单信息
        if (!prodSaleService.save(orderBuilder.bulid())) {
            log.info("保存订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("保存订单异常");
        }
        //保存数据
        prodSaleRecordService.saveBatch(records);
        //保存文件
        sysFileService.saveFile(orderBuilder.getCode(),FileTypeEnum.SALE, FileRecordUtil.toFileDTO(createParams.getFiles()),loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderBuilder.getCode());
    }

    /**
     * 编辑订单
     *
     * @param editParams 编辑对象
     * @return Result
     */
    @Transactional
    public Result<String> editOrder(SaleEditParams editParams) {
        ValidateUtil.validate(editParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdSale prodSale = prodSaleService.querySaleBySaleCode(editParams.getOrderNo(), loginUser);
        new SaleCheck(prodSale).checkNull("销售订单不存在").checkCanEdit("订单不能编辑");
        //查询客户数据
        BaseCustomer baseCustomer = baseCustomerService.queryCustomerByCustomerCode(editParams.getCustomerCode(), loginUser);
        new CustomerCheck(baseCustomer).checkNull("客户不存在");
        SaleBuilder orderBuilder = new SaleBuilder();
        orderBuilder.append(editParams).appendEdit(loginUser).appendStatus(SaleStatusEnum.UN_CHECK.getValue());
        //删除数据
        prodSaleRecordService.deleteOrderGoods(editParams.getOrderNo(), loginUser);
        final List<BigDecimal> quantity = new ArrayList<>();
        //保存商品信息
        List<String> keys = new ArrayList<>();
        List<ProdSaleRecord> records = editParams.getGoods().stream().map(saleGoodsParams -> {
            if (keys.contains(saleGoodsParams.getKey())) {
                log.info("存在相同的物料:{}", saleGoodsParams.getKey());
                throw BusinessExceptionFactory.newException("存在相同的物料");
            }
            keys.add(saleGoodsParams.getKey());
            //销售订单数量
            quantity.add(saleGoodsParams.getQuantity());
            return new SaleRecordBuilder().append(saleGoodsParams).appendCode(orderBuilder.getCode()).appendCreate(loginUser).bulid();
        }).collect(Collectors.toList());
        //保存总数
        orderBuilder.append(quantity.stream().reduce(BigDecimal::add).get());
        //保存总价
        orderBuilder.appendTotal(new BigDecimal(0));
        //编辑订单信息
        if (!prodSaleService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("编辑订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("编辑订单异常");
        }
        //保存数据
        prodSaleRecordService.saveBatch(records);
        //删除文件
        sysFileService.deleteFile(orderBuilder.getCode(), FileTypeEnum.SALE.getValue(),loginUser);
        //保存文件
        sysFileService.saveFile(orderBuilder.getCode(),FileTypeEnum.SALE, FileRecordUtil.toFileDTO(editParams.getFiles()),loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderBuilder.getCode());
    }


    /**
     * 审核通过
     *
     * @param orderNo
     * @return
     */
    @Transactional
    public Result<String> passOrder(String orderNo) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdSale prodSale = prodSaleService.querySaleBySaleCode(orderNo, loginUser);
        new SaleCheck(prodSale).checkNull("销售订单不存在").checkCanCheck("订单已审核");
        SaleBuilder orderBuilder = new SaleBuilder();
        orderBuilder.appendCode(orderNo).appendStatus(SaleStatusEnum.CHECKED.getValue()).appendEdit(loginUser);
        //编辑订单信息
        if (!prodSaleService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("通过订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("通过订单异常");
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderNo);
    }


    /**
     * 完成订单
     *
     * @param orderNo
     * @return
     */
    @Transactional
    public Result<String> finishOrder(String orderNo) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdSale prodSale = prodSaleService.querySaleBySaleCode(orderNo, loginUser);
        new SaleCheck(prodSale).checkNull("销售订单不存在").checkCanFinish("订单未审核或已完成");
        SaleBuilder orderBuilder = new SaleBuilder();
        orderBuilder.appendCode(orderNo).appendStatus(SaleStatusEnum.FINISH.getValue()).appendEdit(loginUser);
        //编辑订单信息
        if (!prodSaleService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("通过订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("通过订单异常");
        }
        //完成后生成对账单
        BillCreateParams createParams = new BillCreateParams();
        createParams.setOrderNos(Arrays.asList(orderNo));
        String billNo = createDispatch.dispatch("createBill", BillSourceEnum.SALE.getValue(), createParams, loginUser);
        log.info("生成对账单:{}",billNo);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderNo);
    }

    /**
     * 打开订单
     *
     * @param orderNo
     * @return
     */
    @Transactional
    public Result<String> openOrder(String orderNo) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdSale prodSale = prodSaleService.querySaleBySaleCode(orderNo, loginUser);
        new SaleCheck(prodSale).checkNull("销售订单不存在").checkCanOpen("订单未完成或已对账");
        SaleBuilder orderBuilder = new SaleBuilder();
        orderBuilder.appendCode(orderNo).appendStatus(SaleStatusEnum.CHECKED.getValue()).appendEdit(loginUser);
        //编辑订单信息
        if (!prodSaleService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("通过订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("通过订单异常");
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderNo);
    }

    /**
     * 删除
     *
     * @param orderNo
     * @return
     */
    @Transactional
    public Result<String> deleteOrder(String orderNo) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdSale prodSale = prodSaleService.querySaleBySaleCode(orderNo, loginUser);
        new SaleCheck(prodSale).checkNull("销售单不存在").checkCanCheck("销售单不能删除");
        SaleBuilder orderBuilder = new SaleBuilder();
        orderBuilder.appendCode(orderNo).appendEdit(loginUser).delete();
        //编辑订单信息
        if (!prodSaleService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("删除订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("删除订单异常");
        }
        //删除数据
        prodSaleRecordService.deleteOrderGoods(orderNo, loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderNo);
    }


    /**
     * 取消
     *
     * @param orderNo
     * @return
     */
    @Transactional
    public Result<String> cancelOrder(String orderNo) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdSale prodSale = prodSaleService.querySaleBySaleCode(orderNo, loginUser);
        new SaleCheck(prodSale).checkNull("销售单不存在").checkCanCancel("订单不能取消");
        SaleBuilder orderBuilder = new SaleBuilder();
        orderBuilder.appendCode(orderNo).appendStatus(SaleStatusEnum.CANCEL.getValue()).appendEdit(loginUser);
        //编辑订单信息
        if (!prodSaleService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("取消订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("取消订单异常");
        }
        //判断退回单是否已取消
        int count = prodSaleBackService.countBack(orderNo, loginUser);
        if (count > 0) {
            log.info("有没有取消的退货单,数量:{}", count);
            throw BusinessExceptionFactory.newException("有没有取消的退货单");
        }
        //判断出库单是否取消
        int outCount = prodSaleOutService.countOut(orderNo, loginUser);
        if (outCount > 0) {
            log.info("存在没有取消的出库单,数量:{}", count);
            throw BusinessExceptionFactory.newException("存在没有取消的出库单");
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderNo);
    }


    /**
     * 订单详情
     *
     * @param orderNo
     * @return
     */
    public Result<SaleVO> viewOrder(String orderNo) {
        LoginUser loginUser = LogInUserUtil.get();
        ProdSale prodSale = prodSaleService.querySaleBySaleCode(orderNo, loginUser);
        new SaleCheck(prodSale).checkNull("销售单不存在");
        SaleVO saleVO = new SaleVO();
        BeanUtil.copyProperties(prodSale, saleVO);
        //查询客信息
        BaseCustomer baseCustomer = baseCustomerService.queryCustomerByCustomerCode(prodSale.getCustomerCode(), loginUser);
        if (ObjectUtil.isNotNull(baseCustomer)) {
            saleVO.setCustomerName(baseCustomer.getCustomerName());
        }
        //查询仓库信息
        WmsWarehouse wmsWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(prodSale.getWarehouseCode(), loginUser);
        if (ObjectUtil.isNotNull(wmsWarehouse)) {
            saleVO.setWarehouseName(wmsWarehouse.getWarehouseName());
        }
        //查询
        List<ProdSaleRecord> prodSaleRecords = prodSaleRecordService.list(orderNo, loginUser);
        Map<String, MaterialModelVO> modelMap = new HashMap<>();

        List<SaleGoodsVO> saleGoodsVOS = prodSaleRecords.stream().map(prodSaleRecord -> {
            MaterialModelVO materialModelVO = modelMap.get(prodSaleRecord.getGoodsCode());
            if (ObjectUtil.isNull(materialModelVO)) {
                materialModelVO = goodsService.queryGoodsByCode(prodSaleRecord.getGoodsCode(), loginUser);
                modelMap.put(prodSaleRecord.getGoodsCode(), materialModelVO);
            }
            return new SaleGoodsBuilder().append(prodSaleRecord).append(materialModelVO).bulid();
        }).collect(Collectors.toList());
        saleVO.setGoods(saleGoodsVOS);
        //查询图片信息
        List<SysFile> files = sysFileService.queryFiles(orderNo, FileTypeEnum.SALE.getValue(),loginUser);
        saleVO.setFiles(FileRecordUtil.toFileVO(files,sysFileConfig));
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, saleVO);
    }
}
